package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/4 18:45
 */

@Slf4j
@Service(version = "1.0.0")
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //redis的key:
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";


    /**
     * 保存小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            //校验：
            if (!ObjectUtil.isAllNotEmpty(video.getPicUrl(), video.getVideoUrl(), video.getUserId())) {
                return null;
            }
            //设置id:
            video.setId(ObjectId.get());
            //设置自增长id:用于后期推荐
            video.setVid(idService.createPid(IdType.VIDEO));
            //设置时间：
            video.setCreated(System.currentTimeMillis());

            //保存到video表:
            mongoTemplate.save(video, "video");
        } catch (Exception e) {
            log.error("保存小视频失败~  video: " + video, e);
        }
        return video.getId().toHexString();
    }


    /**
     * 根据
     *
     * @param videoId
     * @return
     */
    @Override
    public Video queryVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    /**
     * 查询小视频列表：先查询redis存储的vid的videoList
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> findVideoList(Long userId, Integer page, Integer pageSize) {

        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询redis推荐的小视频vid:
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String data = redisTemplate.opsForValue().get(redisKey);

        //vid集合：
        List<Long> vids = new ArrayList<>();

        int reCommentCount = 0;
        if (StrUtil.isNotEmpty(data)) {
            //分页：
            List<String> vidList = StrUtil.split(data, ',');
            //计算分页
            //[0, 10]
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束

            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Long.valueOf(vidList.get(i)));
            }
            reCommentCount = vidList.size();
        }

        if (vids.size() == 0) {

            //计算出已经查询的页数：
            int totalPage = PageUtil.totalPage(reCommentCount, pageSize);
            //没有推荐数据或者redis里面的推荐vid取完了，需要查询系统数据库的vid

            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));//page -totalPage - 1：假如查询了2页，再查询数据库时，需减去已查询的页数再减一开始查询
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);

            pageInfo.setRecords(videoList);

            return pageInfo;
        }

        //根据vid查询videoList:
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);

        return pageInfo;
    }


    /**
     * 关注用户
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            //判断传来的参数是否为空
            return false;
        }
        try {
            //调用mongodb：
            FollowUser followUser = new FollowUser();
            followUser.setObjectId(new ObjectId());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(followUser);

            //保存数据到redis:
            String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
            String hashKey = String.valueOf(followUserId);
            //设置标记，value为1则为关注，没有则为未关注
            redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        } catch (Exception e) {
            log.error("设置关注失败！userId:" + userId, "followUserId:" + followUserId, e);
        }

        return false;
    }

    /**
     * 取消关注
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean unFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            //判断传来的参数是否为空
            return false;
        }

        //如果没有关注这个用户：返回false
        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }
        try {
            //调用mongodb：
            Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
            DeleteResult result = mongoTemplate.remove(query, FollowUser.class);
            if (result.getDeletedCount() > 0) {
                //清除数据redis:
                String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
                String hashKey = String.valueOf(followUserId);
                //设置标记，value为1则为关注，没有则为未关注
                redisTemplate.opsForHash().delete(redisKey, hashKey);
            }
            return true;
        } catch (Exception e) {
            log.error("取消关注失败！userId:" + userId, "followUserId:" + followUserId, e);
        }

        return false;
    }

    /**
     * 查看用户是否已经关注：
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {

        //查询是否关注，查询redis的key即可：
        String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
        String hashKey = String.valueOf(followUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }
}
